<template>
  <el-card>
    <!-- 1.0 标题部分 -->
    <template #header>
      <h3>账号列表</h3>
    </template>

    <!-- 2.0 内容部分 -->
    <div>
      <!-- 2.1 表格 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        size="mini"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="account" label="账号"></el-table-column>
        <el-table-column prop="userGroup" label="用户组"> </el-table-column>
        <el-table-column label="创建时间">
          <template v-slot="{ row }">
            {{ row.ctime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="primary" size="mini" @click="showUserRow(row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="delUser(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2.2 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 2.3 选择按钮 -->
      <div>
        <el-button size="mini" type="danger" @click="delMore"
          >批量删除</el-button
        >
        <el-button size="mini" type="primary" @click="toggleSelection()"
          >取消选择</el-button
        >
      </div>

      <!-- 修改用户的面板 -->
      <el-dialog title="编辑用户" :visible.sync="dialogVisible" width="50%">
        <div>
          <el-form
            :model="editForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="70px"
            class="demo-ruleForm"
            size="mini"
          >
            <el-form-item label="账号" prop="uname">
              <el-input v-model="editForm.uname"></el-input>
            </el-form-item>
            <el-form-item label="用户组" prop="userGroup">
              <el-select v-model="editForm.userGroup" placeholder="请选择">
                <el-option label="普通管理员" value="普通管理员"> </el-option>
                <el-option label="超级管理员" value="超级管理员"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="mini"
            >取 消</el-button
          >
          <el-button type="primary" @click="editDone('ruleForm')" size="mini"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { userList, delUser, delMoreUser, editUser } from '@/api/users.js'
import { checkUName } from '@/utils/validate.js'
import moment from 'moment'

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 3,
      total: 0,
      tableData: [],
      multipleSelection: [],
      dialogVisible: false,
      editForm: {
        uname: '',
        userGroup: ''
      },
      rules: {
        uname: [{ validator: checkUName, trigger: 'blur' }],
        userGroup: []
      }
    }
  },
  created() {
    // console.log(moment(new Date()).format('YYYY-MM-DD HH:mm:ss'))
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data, total } = await userList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      // console.log(data, total)
      this.tableData = data
      this.total = total
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getUserList()
    },
    delUser(id) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const data = await delUser({ id })
          // console.log(data)
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: data.msg
            })
            this.getUserList()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    delMore() {
      this.$confirm('此操作将永久删除这些账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const arr = []
          for (const k of this.multipleSelection) {
            arr.push(k.id)
          }
          if (!arr.length) return
          const data = await delMoreUser({ ids: JSON.stringify(arr) })
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: data.msg
            })
            this.getUserList()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    showUserRow(obj) {
      this.editForm.uname = obj.account
      this.editForm.userGroup = obj.userGroup
      this.editForm.id = obj.id
      this.dialogVisible = true
    },
    editDone(str) {
      this.$refs[str].validate(async valid => {
        if (valid) {
          // 表单验证通过
          const data = await editUser({
            id: this.editForm.id,
            account: this.editForm.uname,
            userGroup: this.editForm.userGroup
          })
          // console.log(data)
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: data.msg
            })
            this.dialogVisible = false
            this.getUserList()
          }
        } else {
          this.$message.error('账号名不能为空！')
          return false
        }
      })
    }
  },
  watch: {
    dialogVisible() {
      if (!this.dialogVisible) {
        // 这个方法必须要求，表单的元素拥有prop属性
        this.$refs.ruleForm.resetFields()
      }
    }
  },
  // 过滤器
  filters: {
    formatTime(str) {
      return moment(str).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin: 20px 0;
}

.el-input {
  width: 193px;
}
</style>
